<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'partner' => '2088621781822784',//用不着
        'seller_id' => 'admin@bagepanzi.com',//用不着
        'sign_type' => 'RSA2',// 直接写死了
        'it_b_pay' => '10m',//用不着
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnxeonWnpDTKGzgbCinHhU60ae2f/I2eDqTteLkQiOq4dqFM9IRQeDkIxd514V6dJUS/40QCHc1sCg0dBXu3R7EA0bn5NJMTEpOD8T8I3dDMKiATnFNJoaeGHZA837ZxG4nhxqManrgLmO8ChV6bTqbIaGOGQJGtTSvwDOqM0IVLst7hN/HJOaHWKY+zPWhp9vz2k12dSbsbA+WryP82eB3Kxe4Su0/IR5ZPnrzCu0AMsZj3HMa686JGk6qzBaWVqNsltnC8CphwWcEv1FW8ilvM61//6w+yi/tdN05zsQUJWiuWAYrQC1rVLaHpmDNHMZrWw0cPsYHvYzndYEXWKEQIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAodLbtG6zDIoyB/9wkGH9x029yW+FS+MEFFQPwtwh1x/aGUhkBhn1Jun3IwHJC1su3Z7CATgxf3J2Fj4QNnLW6RqlVsFBsx8wB7OqWqQl8cnS549yicUnm+Zrvx/iI66sOjBwlbfcad4W9/uCvVFWdYTTo3tTp0i6uy+Wxlnur+em7C1gz4Fv+7KDGoVUm9lTC/1aM68FJoBXW+pY7mWS88F2VACfJfutADI8itdKsQ7p1Wwr/cpYXJrPDGuHYuJmE0GgVUTJFgG7AtXwzyJtZkTSTocU5ABUA1GGeegnhMCHPSt1U2O1E0ruXxJ0PTPNKS8r/J5mzMkOk3zZpEJM+QIDAQAB",
        'private_key' => 'MIIEpAIBAAKCAQEAodLbtG6zDI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MItj47kfaISs/4ivz0HSWA5l1n0C6QtYP/SCY/Pn3Ofk68HEgRG7WlENnNQwNxc7agpF37I3pt9iqDWegYgID+5Glqxfq3oC7u0+3qkwQn8XN7d/bH6z/IyvDuWJVNxb9McYMK1x7H6ov6QKBgQCdInjLFYYLNQ5W/LHch5qgvWSuTtMuvAkiL8OAISz9u5azwt9IXKmmlLhshEKTfIGuYmPB9qmpQ9r4IT0nGzv7itfWcJL8CVm3wH4ei0QuCnd7PerIYNySV/4OTevj9DLFNS/FxI9T47MnZrEUueCO6mtz5/Y/Tc8OpsNakTt+BQKBgQC2uLTLCumhLmdNbkpbwdhMCGa3JjKVcuF9FafNmG01AIt0xDyK0NtvX8QWXh9/wXHXQgaJBWaM8y05Jutbf6XjSzTalVKPDYi7r2G2Hq5iDd2zxeF6zhHuiqpxVorFyuU8q6DX6+UReAZjaDhETe4dIwLiXhiprahHIQMQDq2VEQ=='
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号

    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//    public function getParam(){
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);
//        $no = '5851546514677777712121212';
//        $no = time().rand(1000000,9999999);
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = "2021001156630454";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://xihai.sooqee.cn/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msg'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msg'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }

    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    /**
     * 生成订单
     * @return string|void
     * user_id：用户ID,
     * type：1 课程购买  2 捐赠  3 打赏
     * price：打赏或捐赠的价格，当type为2或者3时传
     * activity_id：捐赠的活动ID，当type为2时，传此值
     */
    public function alipay()
    {
        extract(input());
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
            $money = input('param.money');//价格
            $order_num = input('param.order_num');//充值几个月
            $order_number = date('YmdHis') . str_pad(mt_rand(1, 9999), 6, '0', STR_PAD_LEFT).$user_id;
            $this->body = '戏嗨会员充值';
            $this->subject = '戏嗨会员充值';
            $this->total_amount = $money;
            $this->out_trade_no = $order_number;
            //插入订单表
            $data['order_number'] = $order_number;
            $data['order_userid'] = $user_id;
            $data['order_user_pay'] = $money;
            $data['order_num'] = $order_num;
            $data['order_type'] = 1;
            $data['order_time'] = date('Y-m-d H:i:s');
            $data['order_paytime'] = date('Y-m-d H:i:s');
            $res = Db::table('up_order')->insert($data);
        if($res) {
            $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
            return json_encode($respont);
        } else {
            return json_encode(['status' => 0, 'msg' => '生成订单失败，请联系管理员']);
        }
    }

    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no'];//订单号
                $dataOrder = array();
                $dataOrder['order_paytime'] = $getInfo['gmt_payment'];//支付时间
                Db::startTrans();
                try{
                    $info = Db::table('up_order')->where('order_number',$num)->find();
                    if($info['order_status'] == 1){
                        $dataOrder['order_status'] = 2;//1是未支付  2已支付
                        //更新订单状态
                        Db::table('up_order')->where('order_number',$num)->update($dataOrder);
                        //查询这个订单数据
                        //当前时间
                        $today = date('Y-m-d');

                        $userInfo = Db::table('up_u_user')->where('user_id',$info['order_userid'])->find();
                        $plus = $info['order_num'];
                        if($userInfo['is_vip']==1){//普通
                            $dataOrder1['start_time'] = $today;
                            $dataOrder1['end_time'] = date("Y-m-d",strtotime("+$plus month",strtotime($today)));
                            $dataOrder1['is_vip'] = 2;
                        }elseif ($userInfo['is_vip']==2){//会员
                            $dataOrder1['start_time'] = $userInfo['end_time'];
                            $dataOrder1['end_time'] = date("Y-m-d",strtotime("+$plus month",strtotime($userInfo['end_time'])));
                        }
                        Db::table('up_u_user')->where('user_id',$info['order_userid'])->update($dataOrder1);
                    }
                    Db::commit();
                    die('success');
                }catch (\Exception $e) {
                    Db::rollback();
                    return 'error';
                }
            }
        }
    }
}